package main.java.utils.hxy.thread.thread.batch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

public class BatchTask implements Runnable {
	private static Logger log = LoggerFactory.getLogger (BatchTask.class);
	// private final boolean debug = false; // 调试模式
	private CountDownLatch latch; // 阻断式Task
	private Runnable runnable;

	public BatchTask setRunable(Runnable runnable) {
		this.runnable = runnable;
		return this;
	}

	public BatchTask setCountDownLatch(CountDownLatch latch) {
		this.latch = latch;
		return this;
	}

	@Override
	public void run() {
		try {
			runnable.run();
		} catch (Exception e) {
			log.error("执行错误.", e);
		} finally {
			if (this.latch != null) {
				this.latch.countDown();
			}
		}
	}

	public static BatchTask build(CountDownLatch latch, Runnable runnable) {
		return new BatchTask().setCountDownLatch(latch).setRunable(runnable);
	}

	public static BatchTask build(Runnable runnable) {
		return new BatchTask().setRunable(runnable);
	}
}
